﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;

namespace PmSoft.Data.SqlSugar;

public class SqlSugarConfigBuilder
{
	private readonly IServiceCollection services;

	public SqlSugarConfigBuilder(IServiceCollection services)
	{
		this.services = services;
	}

	/// <summary>
	/// 配置数据库连接
	/// </summary>
	/// <param name="connection">连接字符串</param>
	/// <param name="dbType">数据库类型</param>
	/// <param name="isAutoCloseConnection">是否自动关闭连接</param>
	/// <param name="configId">多库标识</param>
	/// <param name="slaves">从库</param>
	/// <returns></returns>
	/// <exception cref="ArgumentNullException"></exception>
	public SqlSugarConfigBuilder AddConfig(string connection, DbType dbType, bool isAutoCloseConnection, object? configId = null, params SlaveConnection[] slaves)
	{
		if (connection.IsNullOrEmpty()) throw new ArgumentNullException(nameof(connection));

		services.Configure<SqlSugarOptions>(options =>
		{
			options.Connections.Add(new SqlSugarConnection(connection, dbType, isAutoCloseConnection, configId, slaves.ToList()));
		});
		return this;
	}
}
